/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rgbtohex;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author wiker
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        rText.setDocument(new NumberLenghtLimitedDmt(3));
        gText.setDocument(new NumberLenghtLimitedDmt(3));
        bText.setDocument(new NumberLenghtLimitedDmt(3));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        rText = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        gText = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        bText = new javax.swing.JTextField();
        colorLabel = new javax.swing.JLabel();
        hexText = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("RGB转16进制 By WikerYong");
        setPreferredSize(new java.awt.Dimension(389, 100));
        setResizable(false);

        jLabel1.setText("R:");

        rText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                rTextFocusGained(evt);
            }
        });
        rText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rTextKeyReleased(evt);
            }
        });

        jLabel2.setText("G:");

        gText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                gTextFocusGained(evt);
            }
        });
        gText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                gTextKeyReleased(evt);
            }
        });

        jLabel3.setText("B:");

        bText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                bTextFocusGained(evt);
            }
        });
        bText.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                bTextKeyReleased(evt);
            }
        });

        colorLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        colorLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                colorLabelMouseClicked(evt);
            }
        });

        hexText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                hexTextFocusGained(evt);
            }
        });

        jLabel5.setText("十六进制:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rText, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(hexText, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(gText, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bText, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE)
                .addComponent(colorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(colorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(rText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(gText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(bText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(hexText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addGap(0, 2, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void rTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_rTextKeyReleased
        // TODO add your handling code here:
        if(rText.getText().length()==3){
            gText.requestFocus();
        }
        setColor();
    }//GEN-LAST:event_rTextKeyReleased

    private void gTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_gTextKeyReleased
        // TODO add your handling code here:
        if(gText.getText().length()==3){
            bText.requestFocus(true);
        }
        setColor();
    }//GEN-LAST:event_gTextKeyReleased

    private void bTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bTextKeyReleased
        // TODO add your handling code here:
        setColor();
    }//GEN-LAST:event_bTextKeyReleased

    private void rTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rTextFocusGained
        // TODO add your handling code here:
        rText.selectAll();
    }//GEN-LAST:event_rTextFocusGained

    private void gTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_gTextFocusGained
        // TODO add your handling code here:
        gText.selectAll();
    }//GEN-LAST:event_gTextFocusGained

    private void bTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_bTextFocusGained
        // TODO add your handling code here:
        bText.selectAll();
    }//GEN-LAST:event_bTextFocusGained

    private void hexTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_hexTextFocusGained
        // TODO add your handling code here:
        hexText.selectAll();
    }//GEN-LAST:event_hexTextFocusGained
    private JDialog dialog;
    private JColorChooser chooser;

    private void colorLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_colorLabelMouseClicked
        // TODO add your handling code here:
        chooser = new JColorChooser();
        dialog = JColorChooser.createDialog(this, "选择颜色", false, chooser, new ActionListener() // OK button listener
        {
            public void actionPerformed(ActionEvent event) {
                Color color = chooser.getColor();
                int r = color.getRed();
                int g = color.getGreen();
                int b = color.getBlue();
                rText.setText(r+"");
                gText.setText(g+"");
                bText.setText(b+"");
                String hex = toHex(r, g, b);
                hexText.setText(hex);

                colorLabel.setOpaque(true);
                colorLabel.setBackground(new Color(r, g, b));
            }
        }, null);
        dialog.add(chooser);
        dialog.pack();
        dialog.setVisible(true);

    }//GEN-LAST:event_colorLabelMouseClicked

    public void setColor() {
        int r = Integer.parseInt("".equals(rText.getText()) ? "0" : rText.getText());
        int g = Integer.parseInt("".equals(gText.getText()) ? "0" : gText.getText());
        int b = Integer.parseInt("".equals(bText.getText()) ? "0" : bText.getText());
        if (r > 255) {
            r = 255;
            rText.setText("255");
        }
        if (g > 255) {
            g = 255;
            gText.setText("255");
        }
        if (b > 255) {
            b = 255;
            gText.setText("255");
        }

        Color color = new Color(r,g,b);
        String hex = toHex(r, g, b);
        hexText.setText(hex);

        colorLabel.setOpaque(true);
        colorLabel.setBackground(new Color(r, g, b));

    }

    class NumberLenghtLimitedDmt extends PlainDocument {

        private int limit;

        public NumberLenghtLimitedDmt(int limit) {
            super();
            this.limit = limit;
        }

        public void insertString(int offset, String str, AttributeSet attr)
                throws BadLocationException {
            if (str == null) {
                return;
            }
            if ((getLength() + str.length()) <= limit) {

                char[] upper = str.toCharArray();
                int length = 0;
                for (int i = 0; i < upper.length; i++) {
                    if (upper[i] >= '0' && upper[i] <= '9') {
                        upper[length++] = upper[i];
                    }
                }
                super.insertString(offset, new String(upper, 0, length), attr);
            }
        }
    }

    public static String toHex(int r, int g, int b) {
        return "#" + toBrowserHexValue(r) + toBrowserHexValue(g)
                + toBrowserHexValue(b);
    }

    private static String toBrowserHexValue(int number) {
        StringBuilder builder = new StringBuilder(
                Integer.toHexString(number & 0xff));
        String a=builder.toString();
        while (builder.length() < 2) {
            builder.delete(0, 1);
            builder.append("0");
            builder.append(a);
        }
        return builder.toString().toUpperCase();
    }
    //Color转换为16进制显示

    public static String toHexEncoding(Color color) {
        String R, G, B;
        StringBuffer sb = new StringBuffer();

        R = Integer.toHexString(color.getRed());
        G = Integer.toHexString(color.getGreen());
        B = Integer.toHexString(color.getBlue());

        R = R.length() == 1 ? "0" + R : R;
        G = G.length() == 1 ? "0" + G : G;
        B = B.length() == 1 ? "0" + B : B;

        sb.append("0x");
        sb.append(R);
        sb.append(G);
        sb.append(B);

        return sb.toString();
    }

    //把字符串表达的颜色值转换成java.awt.Color
    public static Color parseToColor(final String c) {
        Color convertedColor = Color.ORANGE;
        try {
            convertedColor = new Color(Integer.parseInt(c, 16));
        } catch (NumberFormatException e) {
            // codes to deal with this exception
        }
        return convertedColor;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //new MainFrame().setVisible(true);
                System.out.println(Integer.toHexString(11 & 0xff));
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField bText;
    private javax.swing.JLabel colorLabel;
    private javax.swing.JTextField gText;
    private javax.swing.JTextField hexText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField rText;
    // End of variables declaration//GEN-END:variables
}
